import { watch, nextTick, ref, computed } from 'vue'

function useFixed(wrapperRef, props) {
  const arr = []
  const titleRef = ref('')
  const distance = ref(0)
  const currentIndex = ref(0)
  const TITLE_HEIGHT = 30
  watch(
    () => props.data,
    async () => {
      await nextTick()
      calculate()
    }
  )

  const fixTitleStyle = computed(() => {
    const distanceValue = distance.value
    if (distanceValue > 0 && distanceValue <= TITLE_HEIGHT) {
      return {
        transform: `translateY(${distanceValue - TITLE_HEIGHT}px)`
      }
    }
    return {
      transform: 'translateY(0)'
    }
  })

  function calculate() {
    const children = wrapperRef.value.children
    let height = 0
    arr.push(height)
    for (let i = 0; i < children.length; ++i) {
      height += children[i].offsetHeight
      arr.push(height)
    }
  }

  function onScroll(posY) {
    for (let i = 0; i < arr.length - 1; ++i) {
      if (posY >= arr[i] && posY < arr[i + 1]) {
        titleRef.value = props.data[i].title
        currentIndex.value = i
        distance.value = arr[i + 1] - posY
        break
      }
      if (posY < 0) {
        titleRef.value = ''
      }
    }
  }

  return { onScroll, titleRef, fixTitleStyle, currentIndex }
}

export default useFixed
